<?php
namespace Home\Service;

use Think\Service\BasicService;

class BookGetService extends BasicService {
    public function insert($model) {
        return $this->db->add($model);
    }

    public function AddAll($model) {
        $data = $this->db->addAll($model);
        return $data;
    }

    public function remove($condition) {
        return $this->db->where($condition)->delete();
    }

    public function update($where, $model = array()) {
        return $this->db->where($where)->save($model);
    }

    public function find($condition) {
        return $this->db->where($condition)->find();
    }

    public function query($condition, $limit = array(), $field = '*', $order = '', $join = '') {
        $data = $this->db->join($join)->where($condition)->field($field)->limit($limit['start'], $limit['end'])->order($order)->select();
        return $data;
    }

    public function count($condition) {
        return $this->db->where($condition)->count();
    }

    public function AddOrder($data, $OID) {
        $orderMoney = 0;//书籍总售价
        $orderOldMoney = 0;//书籍总定价
        $this->db->startTrans();
        //生成订单书籍表
        $order_books = array();
        $temp = json_decode($data['books'], true);
        foreach ($temp as $k => $v) {
            $order_book['ob_id'] = 'WXHSOBID_' . uniqid() . rand(10, 99);//订单书籍ID
            $order_book['order_id'] = $OID;//订单id
            $order_book['book_id'] = $v['book_id'];//订单id
            $order_book['ob_name'] = $v['book_name'];//书籍名字
            $order_book['ob_pay_money'] = $v['book_get_price'];//书籍售价
            $order_book['ob_old_money'] = $v['book_old_price'];//书籍定价
            $order_book['ob_num'] = 1;//购买数量
            $order_book['book_id'] = $v['book_id'];//书籍id
            $order_book['isbn'] = $v['isbn'];//isbn
            $order_book['ob_book_pic'] = $v['book_pic'];//书籍图片
            $orderMoney += $v['book_get_price'];
            $orderOldMoney += $v['book_old_price'];
            $order_books[] = $order_book;
        }
        $this->db = M('order_book');
        $addbookOK = $this->db->addAll($order_books);
        //生成订单书籍表成功
        if ($addbookOK) {
            $orderSave['order_id'] = $OID;//订单ID
            $orderSave['user_id'] = $data['user_id'];//用户id
            $orderSave['order_phone'] = $data['order_phone'];//	手机号码（当提交订单的时候直接录入）
            $orderSave['order_address_name'] = $data['order_address_name'];//订单收货人姓名
            $orderSave['order_address'] = $data['order_address'];//订单的地址
            $orderSave['order_num'] = count($order_books);//	订单中的书籍总数
            $orderSave['order_money'] = $orderMoney;//	订单总金额
            $orderSave['order_book_money'] = $orderMoney;//	书籍回收总价
            $orderSave['order_old_money'] = $orderOldMoney;//订单书籍总定价
            $orderSave['order_code'] = 'O_' . time() . rand(0, 9);//	订单编号
            $orderSave['order_start_time'] = date('Y-m-d H:i:s');//	订单开始时间
            $orderSave['order_end_time'] = date('Y-m-d H:i:s', time() + 7 * 24 * 60 * 60);//	结束时间
            $orderSave['order_pay_type'] = 1;//	支付方式（1：微信，2：支付宝）
            $orderSave['order_leixing'] = 3;//	订单的类型 1：租借的订单2：购买的订单3回收
            $orderSave['order_type'] = 1;//	订单状态 1 下单成功 2 人工审核成功
            $orderSave['order_discuss_status'] = 2;//	订单的评论的状态：1：评论过了2：未评论
            $orderSave['order_user_remarks'] = $data['order_remarks'];//订单备注
            $orderSave['order_remarks'] = '微信回收订单';//订单备注
            $orderSave['order_get_time'] = $data['get_time'];//上门时间
            $this->db = M('order');
            $addorderOK = $this->db->add($orderSave);
            if ($addorderOK) {
                $this->db->commit();
                return 1;
            } else {
                $this->db->rollback();
                return -4;//订单主表添加失败
            }

        } else {
            $this->db->rollback();
            return -5;//订单书籍添加失败
        }

    }

    public function GetAllOrder($where, $limit) {
        $order_data = $this->db->where($where)->limit($limit['start'], $limit['end'])->select();
        foreach ($order_data as $k => $v) {
            $order_book = $this->db->join('ts_order_book on ts_order_book.order_id = ts_order.order_id ')->field('ts_order_book.*')->where(array('ts_order.order_id' => $v['order_id']))->select();
            $group_num = $this->GroupOrderGetMoney($v['order_id']);
            $order_data[$k]['bookdatas'] = $order_book;
            $order_data[$k]['group_num'] = $group_num;
        }
        return $order_data;

    }

    public function GetOrderData($where,$files='*') {
        $order_data = $this->db->where($where)->field($files)->find();
        $order_book = M('order_book')
            ->join('left join ts_order_book_user_cl on ts_order_book_user_cl.OB_ID = ts_order_book.ob_id ')
            ->where($where)
            ->select();
        $order_data['bookdatas'] = $order_book;
        return $order_data;
    }


    //取消订单，查看是否参团，是删除进团记录，如果是该团的最后一个则删除团
    public function qxOrder($where, $save) {
        $this->db->startTrans();
        $OK = $this->db->where($where)->save($save);
        //取消订单成功
        if ($OK) {
            $this->db = M('group_order_log');
            $OK1 = $this->db->where(array('ORDER_ID' => $where['ts_order.order_id']))->find();
            //该订单参团了
            if ($OK1) {
                //删除该订单参团记录
                $where2['ORDER_ID'] = $where['ts_order.order_id'];
                $save2['STATE'] = -1;
                $OK2 = $this->db->where($where2)->save($save2);
                if ($OK2) {
                    //查看参团人数
                    $whereNum['GROUP_ID'] = $OK1['GROUP_ID'];
                    $whereNum['STATE'] = 1;
                    $num = $this->db->where($whereNum)->count();
                    //该团参团人数为0 删除团
                    if ($num == 0) {
                        $this->db = M('hs_group_order');
                        $OK3 = $this->db->where(array('ID' => $OK1['GROUP_ID']))->delete();
                        //删除团成功 结束
                        if ($OK3) {
                            $this->db->commit();
                            return 1;
                        } else {
                            $this->db->rollback();
                            return -1;
                        }
                    } else {
                        //查看是否是团长
                        $whereTZ['join_order_id'] = $where['ts_order.order_id'];
                        $JoinData = M('hs_group_order_view')->where($whereTZ)->find();
                        if ($JoinData && $JoinData['join_user_id'] == $JoinData['group_user_id']) {
                            $whereNogroupUser['GROUP_ID'] = $OK1['GROUP_ID'];
                            $whereNogroupUser['USER_ID'] = array('NEQ',$JoinData['group_user_id']);
                            $NogroupUser = M('group_order_log')->where($whereNogroupUser)->find();
                            $whereNewTZ['ID'] = $OK1['GROUP_ID'];
                            $saveNewTZ['GROUP_USER_ID'] = $NogroupUser['USER_ID'];
                            $this->db = M('hs_group_order');
                            $OK4 = $this->db->where($whereNewTZ)->save($saveNewTZ);
                            //修改组长失败
                            if (!$OK4) {
                                //删除该订单参团记录失败
                                $this->db->rollback();
                                return -4;
                            }
                        }
                        //不删团 结束
                        $this->db->commit();
                        return $num;
                    }
                } else {
                    //删除该订单参团记录失败
                    $this->db->rollback();
                    return -1;
                }

            } else {
                //没参团
                $this->db->commit();
                return 1;
            }
        } else {
            $this->db->rollback();
            return -1;
        }


    }

    //计算订单拼团人数
    public function GroupOrderGetMoney($order_id) {
        $logData = M('group_order_log')->where(array('ORDER_ID' => $order_id))->find();
        $num = M('group_order_log')->where(array('GROUP_ID' => $logData['GROUP_ID']))->count();
        return $num;
    }
}


?>